// hooks/useDictData.ts
import { useState, useEffect } from 'react';
import { request } from '@/utils/request';

export interface DictItem {
  id: number;
  label: string;
  value: string;
  dictType: string;
}

/**
 * 获取字典数据
 * @param type 字典类型，如 'member_appraiser_level'、'appraisal_category'
 */
export const useDictData = (type: string) => {
  const [data, setData] = useState<DictItem[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchDict = async () => {
    setLoading(true);
    try {
      const res: DictItem[] = await request.get('/system/dict-data/type', { type }, false);
      setData(res);
    } catch (err) {
      console.error(`获取字典类型 ${type} 失败`, err);
      setData([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (type) fetchDict();
  }, [type]);

  return { data, loading, fetchDict };
};
